package com.baosight.risk.service.fltd.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baosight.risk.api.fltd.AuthoTypeService;
import com.baosight.risk.api.xtzy.IXtzyOrgService;
import com.baosight.risk.mapper.xtzy.XtzyOrgMapper;
import com.baosight.risk.service.fltd.vo.FlaaNodeAuthoTypeVO;
import com.baosight.risk.service.xtzy.entity.XtzyOrg;
import com.baosight.risk.service.xtzy.entity.XtzyUser;

import lombok.extern.slf4j.Slf4j;

/**
 * 组织机构权限 orgRiskRole
 */
@Slf4j
@Service("orgRiskRole")
public class OrgRiskRoleAuthoTemplate implements AuthoTypeService {
    @Autowired
    private XtzyOrgMapper orgMapper;
    @Autowired
    private AuthoTypeTemplate authoTypeService;
    @Autowired
    private IXtzyOrgService orgService;

    @Override
    public Map<String, Object> parse(String template, Map<String, Object> param) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();
        FlaaNodeAuthoTypeVO authInfo = (FlaaNodeAuthoTypeVO) param.get("authInfo");
        XtzyUser currentUser = (XtzyUser) param.get("currentUser");
        //流程参与者
        List<XtzyUser> userList = (List<XtzyUser>) param.get("userList");
        String nodeAuth = authInfo.getNodeAuth();
        String roleId = authInfo.getRoleCode();
        FltdTaskVO currentTask = (FltdTaskVO) param.get("currentTask");
        String manageCompCode = currentTask.getManageCompCode();
        
        if(StringUtils.isNotBlank(manageCompCode)){
            //全部 or 本单位
            if (AuthoTypeService.ORG_ALL.equals(nodeAuth) || AuthoTypeService.ORG_ORG.equals(nodeAuth)) {
                XtzyOrg oParam = new XtzyOrg();
                oParam.setBusiCompCode(manageCompCode);
                XtzyOrg org = orgMapper.selectOne(oParam);
                if(StringUtils.isNotBlank(org.getBusiCompCode())){
	            	List<XtzyUser> newUsers = orgService.getUserAndOrgCodeAndRoleId(org.getBusiOrgCode(), roleId);
	                authoTypeService.unionUsers(userList, newUsers);
                }
            } else {
            	throw new Exception("无权限配置");
            }
        }else{
        	throw new Exception("管理单位不能为空");
        }

        return resultMap;
    }
}
